<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="always">
        <template #header>
          <div>试题录入</div>
        </template>
        <el-form ref="questionForm" :model="formData" :rules="rules" label-width="120px">
          <el-form-item prop="subjectID" label="学科：">
            <el-select v-model="formData.subjectID" style="width: 400px" @change="changeSubject">
              <el-option v-for="item in subjectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="catalogID" label="目录：">
            <el-select v-model="formData.catalogID" style="width: 400px">
              <el-option v-for="item in diretorysList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item  prop="enterpriseID" label="企业：">
            <el-select v-model="formData.enterpriseID" style="width: 400px">
              <el-option v-for="item in compList" :key="item.id" :label="item.company" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市：" prop="city">
            <el-select v-model="formData.province" style="width: 198px" @change="changeProvince">
              <el-option v-for="item,index in provinceList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
            <el-select v-model="formData.city" style="width: 198px;margin-left: 4px;">
              <el-option v-for="item,index in cityList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item  prop="direction" label="方向：">
            <el-select v-model="formData.direction" style="width: 400px">
              <el-option v-for="item,index in direction" :key="index" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item  prop="questionType" label="题型：">
            <el-radio-group v-model="formData.questionType" @input="changeOptions" >
              <el-radio v-for="item,index in questionType" :key="index" :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item  prop="difficulty" label="难度：">
            <el-radio-group v-model="formData.difficulty">
              <el-radio v-for="item,index in difficulty" :key="index" :label="item.value">{{ item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item  prop="question" label="题干：">
            <quillEditor
            v-model="formData.question"
            :options="editorOption"
            ></quillEditor>
          </el-form-item>
          <el-form-item v-if="this.formData.questionType !== '3' " prop="options" label="选项："  style="width: 700px">
              <el-radio-group :value="radioIndex" @input="changeRadioIndex" v-if="this.formData.questionType === '' || this.formData.questionType === '1' ">
                <el-radio
                  v-for="item,index in this.formData.options.slice(0,4)"
                  :key="item.code"
                  :label="index"
                  style="padding-bottom: 20px"
                  >
                  <span>{{ item.code }}：</span>
                <el-input v-model="item.title" style="width: 240px"></el-input>
                <el-upload
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :show-file-list="false"
                  style="margin-left: 4px"
                  >
                  <span class="img" style="color: #000">上传图片</span>
                  <i class="el-icon-circle-close"></i>
                </el-upload>
                </el-radio>
              </el-radio-group>
              <el-checkbox-group v-model="checkIndex" @input="changeCheckIndex" v-else-if="this.formData.questionType === '2' ">
                <el-checkbox
                  v-for="item,index in this.formData.options"
                  :key="item.code"
                  :label="index"
                  style="padding-bottom: 20px"
                  >
                  <span>{{ item.code }}：</span>
                <el-input v-model="item.title" style="width: 240px"></el-input>
                <el-upload
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :show-file-list="false"
                  style="margin-left: 4px"
                  >
                  <span class="img" style="color: #000">上传图片</span>
                  <i class="el-icon-circle-close"></i>
                </el-upload>
                </el-checkbox>
              </el-checkbox-group>
              <div>
                <el-button @click="addOption" :disabled="this.formData.questionType !== '2'" type="danger" size="small">+增加选项与答案</el-button>
              </div>
          </el-form-item>
          <el-form-item prop="videoURL" label="解析视频：">
            <el-input v-model="formData.videoURL" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item prop="answer" label="答案解析：">
            <quillEditor
             v-model="formData.answer"
            :options="editorOption"
            ></quillEditor>
          </el-form-item>
          <el-form-item  prop="remarks" label="题目备注：">
            <el-input v-model="formData.remarks" type="textarea" rows="4" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item  prop="remarks" label="试题标签：">
            <el-select
            v-model="tagstjList"
            multiple
            style="width: 400px"
            placeholder="请选择试题标签"
            >
              <el-option v-for="item in tagsList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addQuestion">确认提交</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 富文本编辑器配置
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 学科接口方法
import { simple as subSimple } from '@/api/hmmm/subjects'
// 目录接口方法
import { simple as direSimple } from '@/api/hmmm/directorys'
// 标签接口方法
import { simple as tagsSimple } from '@/api/hmmm/tags'
// 企业接口方法
import { detail as compDetail } from '@/api/hmmm/companys'
// 城市接口方法
import { provinces, citys } from '@/api/hmmm/citys'
// 同用常量方法 { 方向 题型 难度 复选框组 }
import { direction, questionType, difficulty, checkGroup } from '@/api/hmmm/constants'
// 引入提交表单接口方法
import { add as addQuestion, detail as quesDetail, update as quesUpdate } from '@/api/hmmm/questions'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      // 提交表单
      formData: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        // options: {
        //   code: '', // 代码
        //   title: '', // 标题
        //   img: '', // 图片UIL
        //   isRight: '' // 是否正确答案
        // }, // 选项
        options: [
          { isRight: 0, code: 'A', title: '', img: '' },
          { isRight: 0, code: 'B', title: '', img: '' },
          { isRight: 0, code: 'C', title: '', img: '' },
          { isRight: 0, code: 'D', title: '', img: '' }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '' // 题目备注
      },
      // 学科简单列表
      subjectList: [],
      // 目录简单列表
      diretorysList: [],
      // 标签简单列表
      tagsList: '',
      // 标签列表
      tagstjList: [],
      // 企业列表
      compList: [],
      // 城市列表
      provinceList: [],
      cityList: [],
      // 方向
      direction,
      // 题型
      questionType,
      // 难度
      difficulty,
      // 复选框数据
      checkGroup,
      // 规则校验
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'blur' }
        ], // 学科
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'blur' }
        ], // 目录
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ], // 企业
        city: [
          { required: true, message: '请选择地区', trigger: 'blur' }
        ], // 地区
        direction: [
          { required: true, message: '请选择方向', trigger: 'blur' }
        ], // 方向
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ], // 题干
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ] // 答案解析
      },
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            // [{ header: 1 }, { header: 2 }], // 1、2级标题
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序，无序列表
            // [{ script: 'sub' }, { script: 'super' }] // 上标/下标
            ['blockquote'], // 引用 代码块
            ['code-block', 'image', 'link'] // 图片，链接
          ]
        },
        placeholder: '' // 默认显示为空
      }
    }
  },
  computed: {
    // 与单选框双向绑定
    radioIndex: {
      get () {
        return this.formData.options.findIndex(item => item.isRight === 1)
      },
      set () {}
    },
    // 与双选框双向绑定
    checkIndex: {
      get () {
        const index = []
        const arr = JSON.parse(JSON.stringify(this.formData.options))
        let idx = arr.findIndex(item => item.isRight === 1)
        while (idx !== -1) {
          index.push(idx)
          arr[idx].isRight = 0
          idx = arr.findIndex(item => item.isRight === 1)
        }
        return index
      },
      set () {}
    },
    // 试题标签
    tags () {
      return this.tagstjList.join(',')
    }
  },
  created () {
    if (this.$route.query.id) this.getQuesDetail(this.$route.query.id)
    // console.log(this.$route.query.id)
    // 获取学科列表
    this.getSubSimList()
    // 获取企业列表
    this.getCompDetail()
    // 获取城市列表
    this.getProvinceList()
  },
  methods: {
    // 提交表单 录入基础题库
    async addQuestion () {
      // 对表单整体校验
      this.$refs.questionForm.validate(isOk => {
        if (isOk) {
          if (this.formData.questionType === '1') {
            this.formData.options.splice(4, this.formData.options.length - 4)
          } else if (this.formData.questionType === '3') {
            this.formData.options = [
              { isRight: 0, code: 'A', title: '', img: '' },
              { isRight: 0, code: 'B', title: '', img: '' },
              { isRight: 0, code: 'C', title: '', img: '' },
              { isRight: 0, code: 'D', title: '', img: '' }
            ]
          }
          if (!this.tagstjList) {
            this.formData = { ...this.formData, tags: this.tags }
          }
          if (this.$route.query.id) {
            this.$nextTick(async () => {
              await quesUpdate({ ...this.formData, id: +this.$route.query.id })
              this.$message.success('修改成功')
              this.$router.push('/questions/list')
            })
          } else {
            this.$nextTick(async () => {
              await addQuestion(this.formData)
              this.$message.success('添加成功')
              this.$router.push('/questions/list')
            })
          }
        }
      })
    },
    // 切换 单选、复选、简答题型 事件
    changeOptions () {
      this.formData.options.map(item => {
        item.isRight = false
      }
      )
    },
    // 增加复选框点击事件
    addOption () {
      this.formData.options.push({ isRight: false, code: this.checkGroup[this.formData.options.length + 1], title: '', img: '' })
    },
    // 单选框组 切换答案事件
    changeRadioIndex (index) {
      // console.log(index)
      for (let i = 0; i < this.formData.options.length; i++) {
        this.formData.options[i].isRight = i === index ? 1 : 0
      }
    },
    // 复选框组 切换答案事件
    changeCheckIndex (index) {
      // console.log(index)
      for (let i = 0; i < this.formData.options.length; i++) {
        this.formData.options[i].isRight = index.includes(i) ? 1 : 0
      }
    },
    // 改变学科事件 联动目录，标签
    changeSubject () {
      this.getDirSimList()
      this.getTagsSimList()
    },
    // 改变城市事件 联动区域
    changeProvince (pname) {
      this.getCityList(pname)
    },
    // 获取问题详情
    async getQuesDetail (id) {
      const res = await quesDetail(id)
      this.formData = res.data
    },
    // 获取学科简单列表
    async getSubSimList () {
      const res = await subSimple()
      this.subjectList = res.data
      // console.log(this.subjectList)
    },
    // 获取目录简单列表
    async getDirSimList () {
      const res = await direSimple(this.formData.subjectID)
      this.diretorysList = res.data
    },
    // 获取标签简单列表
    async getTagsSimList () {
      const res = await tagsSimple(this.formData.subjectID)
      // this.tagsList = res.data.map(item => item.label).join(',')
      this.tagsList = res.data
    },
    // 获取企业详情
    async getCompDetail () {
      const res = await compDetail()
      this.compList = res.data.items
    },
    // 获取城市列表
    getProvinceList () {
      this.provinceList = provinces()
    },
    // 获取区域列表
    getCityList (pname) {
      this.cityList = citys(pname)
    }
  }
}
</script>

<style scoped lang="scss">
.avatar-uploader {
    display: inline-block;
    vertical-align: middle;
    position: relative;
    // line-height: 1;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width: 100px;
    height: 60px;
    line-height: 60px;
    .img{
      margin-left: 22px;
    }
    i {
    position: absolute;
    right: 0;
    top: 0;
    -webkit-transform: translate(50%,-50%);
    transform: translate(50%,-50%);
    background: #fff;
    font-size: 18px;
    color: #000;
    }
  }
::v-deep .ql-editor {
    height: 200px
}
</style>
